package main

import (
	"flag"
	"log"
	"os"
	"os/signal"
	"path/filepath"

	"github.com/linchao/zkp_auth/cmd"
	cp_zkp "github.com/linchao/zkp_auth/internal/cpzkp"
	"github.com/linchao/zkp_auth/internal/server"
	"github.com/linchao/zkp_auth/models"
)

func init() {
	cmd.SetupFlags()
}

func main() {
	var runServerInBackground = flag.Bool("server", false, "run grpc server in the background")
	var initDB = flag.Bool("init-db", false, "initialize database")
	var dbPath = flag.String("db-path", "./data/auth.db", "path to SQLite database file")
	flag.Parse()

	// 创建数据目录
	dbDir := filepath.Dir(*dbPath)
	if _, err := os.Stat(dbDir); os.IsNotExist(err) {
		if err := os.MkdirAll(dbDir, 0755); err != nil {
			log.Fatalf("Failed to create database directory: %v", err)
		}
	}

	// 单独初始化数据库
	if *initDB {
		log.Printf("Initializing database at %s...", *dbPath)
		err := models.InitDB(*dbPath)
		if err != nil {
			log.Fatalf("Failed to initialize database: %v", err)
		}
		log.Printf("Database initialized successfully")
		// 如果只是初始化数据库，则不启动服务器
		if !*runServerInBackground {
			return
		}
	}

	// 启动服务器
	if *runServerInBackground {
		cpzkpParams, err := cp_zkp.NewCPZKP()
		if err != nil {
			log.Fatal("error generating system parameters:", err)
		}

		cfg := &server.Config{
			CPZKP:  cpzkpParams,
			DBPath: *dbPath,
		}

		// 创建并后台启动gRPC服务器
		go server.RunServer(cfg)

		// 等待中断信号以优雅退出
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt)
		<-c

		log.Println("Server shutting down...")
		return
	}

	// 执行Cobra命令（客户端操作）
	if err := cmd.RootCmd.Execute(); err != nil {
		log.Fatal("error:", err)
	}
}
